<?php 
    include("../includes/connect_db.php");
    include("../includes/core.php"); 

    $act = $_POST['act'];

    if (!isset($_SESSION['idUser'])) {
        $iduser = 0;
    } else {
        $iduser = $_SESSION['idUser'];
    }

    switch ($act) {
        case '1':
        	$searchKey = $_POST['key'];
        	
        	$sql = "SELECT * FROM menu WHERE nama LIKE '%$searchKey%' OR nama LIKE '%$searchKey%' ORDER BY nama ASC LIMIT 5";
            $query = mysql_query($sql);
            $data = array();
            while ($baris = mysql_fetch_array($query)) {
              $data[] = array("id"=>$baris['id'],"nama"=>$baris['nama'],"kode"=>$baris["kode"]);
            }
            echo json_encode($data);
            break;
        
        case '2':
            $order_menu = $_POST["order_menu"];
            $no_meja = $_POST["no_meja"];
            $tanggal = $_POST["tanggal"];
            $idresto = $_POST["idresto"];
            $act_form = $_POST["act_form"];

            // INSERT KE RESTO IF NEW
            if ($act_form == "new") {
                $sql_insert_resto = "INSERT INTO resto (no_meja, tanggal, iduser) VALUES ('$no_meja', '$tanggal', '$iduser')";
                $query_insert_resto = mysql_query($sql_insert_resto);
                $idresto = mysql_insert_id();
            }

            // INSERT KE RESTO MENU
            if (!empty($order_menu)) {
                foreach ($order_menu as $value) {
                    $sql_check = "SELECT * FROM resto_menu WHERE idresto = '$idresto' AND idmenu = '$value[0]' AND bill = '1'";
                    $query_check = mysql_query($sql_check);
                    if (mysql_num_rows($query_check) > 0) {
                        $query_check = mysql_query($sql_check);
                        $check = mysql_fetch_array($query_check);
                        $jumlah = $check[jumlah] + $value[1];
                        $sql_insert_resto_menu = "UPDATE resto_menu SET jumlah = '$jumlah' WHERE id = '$check[id]'";
                    } else {
                        $sql_menu = "SELECT * FROM menu WHERE id = '$value[0]'";
                        $query_menu = mysql_query($sql_menu);
                        $menu = mysql_fetch_array($query_menu);

                        $sql_insert_resto_menu = "INSERT INTO resto_menu (idresto, idmenu, jumlah, harga, harga_ori) VALUES ('$idresto', '$value[0]', '$value[1]', '$menu[harga]', '$menu[harga]')";
                    }

                    $query_insert_resto_menu = mysql_query($sql_insert_resto_menu);
                }
            }
            echo "sukses";
            break;

        default:
            # code...
            break;
    }

?>